package com.useeinfo.oa.open.mobile.charts;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.HttpClient;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.ApplicationModuleBiz;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.biz.SystemUserOrganizationBiz;
import com.useeinfo.oa.modules.base.entity.ApplicationModule;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.entity.SystemUserOrganization;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 手机图表
 */
@RestController
@RequestMapping("/stat")
public class ChartsManageAction {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private EnterpriseBiz enterpriseBiz;

    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;

    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;



    /**
     * Charts 工单完成率
     * @param type （周，月，季度）
     * @param enterpriseId 企业id
     * @return JSONObject
     */
    @RequestMapping("/dataReport")
    public JSONObject getDailyCheck(String type, String enterpriseId) {
        // 巡检
        String dailyCheckDataUrl = Configuration.getConfigurationByName("hostUrl") + "inspectionCharts/getOrderData.action";
        // 维保
        String ppmDataUrl = Configuration.getConfigurationByName("hostUrl") + "maintainCharts/getOrderData.action";
        // 维修
        String mrDataUrl = Configuration.getConfigurationByName("hostUrl") + "repairOrderCharts/getOrderData.action";
        // 任务工单
        String taskDataUrl = Configuration.getConfigurationByName("hostUrl") + "taskOrderCharts/getOrderData.action";
        // 周报月报季度报工单完成率
        String completedPercentUrl = Configuration.getConfigurationByName("hostUrl") + "completedOrdersPercentAPI/getOrdersPercent.action";

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("type", type);
        dataMap.put("enterpriseId", enterpriseId);

        JSONObject completedPercentObject = JSONObject.parseObject(HttpClient.doPost(completedPercentUrl, dataMap));
        JSONObject result = new JSONObject();
        JSONObject object = new JSONObject();

        //dataTitle
        JSONArray dataTitle = new JSONArray();
        //pieData工单发单占比率使用
        JSONArray pieData = new JSONArray();
        //dataArray每日(或季度)总的工单完成率
        JSONArray dataArray = new JSONArray();

        //按企业下的各模块来计算图表
        QueryParam queryParam1 = new QueryParam("-1", "-1");
        queryParam1.getSqlMap().put("enterpriseId", enterpriseId);
        List<ApplicationModule> applicationModules = applicationModuleBiz.findList(queryParam1);
        for (ApplicationModule x : applicationModules) {
            if ("MAINTAIN".equals(x.getRemark())) {
                //ppmData 维保图表相关
                dataTitle.add("PPM");
                JSONObject ppm = JSONObject.parseObject(HttpClient.doPost(ppmDataUrl, dataMap));
                JSONObject ppmObject1 = (JSONObject) ppm.get("0");
                JSONObject ppmObject2 = (JSONObject) ppm.get("1");
                JSONArray ppmArrayData = new JSONArray();
                ppmArrayData.add(ppmObject1);
                ppmArrayData.add(ppmObject2);
                object.put("ppmData", ppmArrayData);
                ppmObject1.put("stack", "数据报告");
                dataArray.add(ppmObject1);
                JSONObject ppmPieObject = new JSONObject();
                ppmPieObject.put("name", "PPM");
                JSONArray ppmArray = ppmObject1.getJSONArray("data");
                ppmPieObject.put("value", getSum(ppmArray));
                pieData.add(ppmPieObject);
            } else if ("INSPECTION".equals(x.getRemark())) {
                //dailyCheck巡检相关图表
                dataTitle.add("Daily Check");
                JSONObject dailyCheck = JSONObject.parseObject(HttpClient.doPost(dailyCheckDataUrl, dataMap));
                JSONObject dailyObject = (JSONObject) dailyCheck.get("0");
                JSONObject dailyObject2 = (JSONObject) dailyCheck.get("1");
                JSONArray dailyCheckData = new JSONArray();
                dailyCheckData.add(dailyObject);
                dailyCheckData.add(dailyObject2);
                object.put("dailyCheckData", dailyCheckData);
                JSONArray dailyArray = dailyObject.getJSONArray("data");
                dailyObject.put("stack", "数据报告");
                dataArray.add(dailyObject);
                JSONObject dailyPieObject = new JSONObject();
                dailyPieObject.put("name", "Daily Check");
                dailyPieObject.put("value", getSum(dailyArray));
                pieData.add(dailyPieObject);
            } else if ("REPAIR".equals(x.getRemark())) {
                //mrData 维修图表相关
                dataTitle.add("M&R");
                JSONObject mr = JSONObject.parseObject(HttpClient.doPost(mrDataUrl, dataMap));
                JSONObject mrObject = (JSONObject) mr.get("0");
                JSONObject mrObject2 = (JSONObject) mr.get("1");
                JSONArray mrArrayData = new JSONArray();
                mrArrayData.add(mrObject);
                mrArrayData.add(mrObject2);
                object.put("mrData", mrArrayData);
                JSONArray mrArray = mrObject.getJSONArray("data");
                JSONObject mrPieObject = new JSONObject();
                mrPieObject.put("name", "M&R");
                mrPieObject.put("value", getSum(mrArray));
                pieData.add(mrPieObject);
                mrObject.put("stack", "数据报告");
                dataArray.add(mrObject);
            }
            else if ("TASK".equals(x.getRemark())) {
                //taskData 维修图表相关
                dataTitle.add("Others");
                JSONObject task = JSONObject.parseObject(HttpClient.doPost(taskDataUrl, dataMap));
                JSONObject taskObject = (JSONObject) task.get("0");
                JSONObject taskObject2 = (JSONObject) task.get("1");
                JSONArray taskArrayData = new JSONArray();
                taskArrayData.add(taskObject);
                taskArrayData.add(taskObject2);
                object.put("taskData", taskArrayData);
                JSONArray taskArray = taskObject.getJSONArray("data");
                JSONObject taskPieObject = new JSONObject();
                taskPieObject.put("name", "Others");
                taskPieObject.put("value", getSum(taskArray));
                pieData.add(taskPieObject);
                taskObject.put("stack", "数据报告");
                dataArray.add(taskObject);
            }
        }

        dataArray.add(completedPercentObject.get("percentObject"));
        object.put("data", dataArray);
        //工单发单占比率使用
        object.put("pieData", pieData);
        // dataTitle
        dataTitle.add("completion rate（%）");
        object.put("dataTitle", dataTitle);
        //dataName日期
        object.put("dataName", completedPercentObject.get("dateTimes"));
        //报告周期
        String start="";
        String end=DateTimeUtils.formatDateToStringWithOnlyDate1(new Date()).replaceAll("-","/");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        if("week".equals(type)){
            start=DateTimeUtils.formatDateToStringWithOnlyDate1(DateTimeUtils.getFirstDateOfWeek(new Date()));
        }else if("month".equals(type)){
            start=DateTimeUtils.formatDateToStringWithOnlyDate1(c.getTime());
        }else{
            start=DateTimeUtils.getStartDateBySeason(DateTimeUtils.getSeason(new Date())).replaceAll("-","/");
        }
        object.put("period", "报告周期："+start+"-"+end);

        object.put("dataTitle", dataTitle);
        //部门数据
        QueryParam queryParam = new QueryParam("-1", "-1");
        queryParam.getSqlMap().put("enterpriseId", enterpriseId);
        List<Organization> organizationList = organizationBiz.findList(queryParam);
        JSONArray organizationArray = new JSONArray();
        organizationList.forEach(x -> {
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("id", x.getId());
            jsonObject3.put("name", x.getOrganizationName());
            organizationArray.add(jsonObject3);
        });
        object.put("organizationArray", organizationArray);

        result.put("code", "00000000");
        result.put("msg", "success");
        result.put("data", object);
        return result;
    }

    /**
     * 发单数求和
     *
     * @param jsonArray
     * @return
     */
    public String getSum(JSONArray jsonArray) {
        int sum = 0;
        for (Object o : jsonArray) {
            sum += StringConverters.null2Int(o);
        }
        return StringConverters.null2String(sum);
    }

    /**
     * 部门人员工时
     */
    @RequestMapping("/getOrganizationHours")
    @ResponseBody
    public ResultDto getOrganizationHours(String type, String organizationId, String enterpriseId) {
        Organization organization = organizationBiz.findModel(StringConverters.null2Long(organizationId));
        String organizationName = organization.getOrganizationName();
        JSONObject jsonObject = new JSONObject();
        JSONArray dataName = new JSONArray();//人员名称
        JSONArray dataTitle = new JSONArray();//模块名称
        JSONArray data = new JSONArray();//人员工时数

        String start;
        String end;
        if (type.equals("week")) {//周报
            start = DateTimeUtils.formatDateToString(DateTimeUtils.getFirstDateOfWeek(new Date()));//获取本周一的日期
            end = DateTimeUtils.formatDateToString(DateTimeUtils.getLastDateOfWeek(new Date()));//本周日的日期
        } else if (type.equals("month")) {//月报
            start = DateTimeUtils.formatDateToString(DateTimeUtils.getFirstDateOfMonth(new Date())); //获取本月初的日期
            end = DateTimeUtils.formatDateToString(DateTimeUtils.getLastDateOfMonth(new Date()));//本月末的日期
        } else {//季度报
            start = DateTimeUtils.formatDateToString(DateTimeUtils.getCurrentQuarterStartTime(new Date()));//获取当年的第一天
            end = DateTimeUtils.formatDateToString(DateTimeUtils.getCurrentQuarterEndTime(new Date()));//获取当年的最后一天
        }

        QueryParam queryParam = new QueryParam("-1", "-1");
        queryParam.getSqlMap().put("organizationId", organizationId);
        queryParam.getSqlMap().put("enterpriseId", enterpriseId);
        queryParam.setSqlOrder("order by systemUser.id");
        List<SystemUserOrganization> systemUserOrganizations = systemUserOrganizationBiz.findList(queryParam);

        if (systemUserOrganizations.size() < 1) {
            // 暂无人员
            dataName.add("No personnel");
        } else {
            for (SystemUserOrganization x : systemUserOrganizations) {
                dataName.add(x.getSystemUser().getUserName());
            }
        }


        JSONArray zo = new JSONArray();
        zo.add(0,0);


        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("organizationId", organizationId);
        dataMap.put("startDateTime", start);
        dataMap.put("endDateTime", end);
        dataMap.put("enterpriseId", enterpriseId);

        QueryParam queryParam1 = new QueryParam("-1", "-1");
        queryParam1.getSqlMap().put("enterpriseId", enterpriseId);
        List<ApplicationModule> applicationModules = applicationModuleBiz.findList(queryParam1);
        for (ApplicationModule x : applicationModules) {
            if ("MAINTAIN".equals(x.getRemark())) {        //维护保养
                dataTitle.add("PPM");
                JSONObject maintainData = new JSONObject();
                maintainData.put("name", "PPM");
                maintainData.put("stack", "数据报告");
                maintainData.put("type", "bar");
                maintainData.put("barWidth", "10");
                maintainData.put("markLine", "");
                String ppmDataUrl = Configuration.getConfigurationByName("hostUrl") + "maintainCharts/getHoursData.action";
                JSONArray ppm = JSONObject.parseArray(HttpClient.doPost(ppmDataUrl, dataMap));
                if (ppm.size()<1) {
                    maintainData.put("data", zo);
                } else {
                    maintainData.put("data", ppm);
                }

                data.add(maintainData);
            } else if ("INSPECTION".equals(x.getRemark())) { //抄表巡检
                dataTitle.add("Daily Check");
                JSONObject inspectionData = new JSONObject();
                inspectionData.put("name", "Daily Check");
                inspectionData.put("stack", "数据报告");
                inspectionData.put("type", "bar");
                inspectionData.put("barWidth", "10");
                inspectionData.put("markLine", "");
                String dailyCheckDataUrl = Configuration.getConfigurationByName("hostUrl") + "inspectionCharts/getHoursData.action";
                JSONArray dailyCheck = JSONObject.parseArray(HttpClient.doPost(dailyCheckDataUrl, dataMap));
                // 判断是否为空
                if (dailyCheck.size()<1) {
                    inspectionData.put("data", zo);
                } else {
                    inspectionData.put("data", dailyCheck);
                }
                data.add(inspectionData);
            } else if ("REPAIR".equals(x.getRemark())) {        //维修管理
                dataTitle.add("M&R");
                JSONObject repairData = new JSONObject();
                repairData.put("name", "M&R");
                repairData.put("stack", "数据报告");
                repairData.put("type", "bar");
                repairData.put("barWidth", "10");
                repairData.put("markLine", "");
                String mrDataUrl = Configuration.getConfigurationByName("hostUrl") + "repairOrderCharts/getHoursData.action";
                JSONArray mr = JSONObject.parseArray(HttpClient.doPost(mrDataUrl, dataMap));
                if (mr.size()<1) {
                    repairData.put("data", zo);
                } else {
                    repairData.put("data", mr);
                }

                data.add(repairData);
            }
            else if ("TASK".equals(x.getRemark())) {        //任务单管理
                dataTitle.add("Others");
                JSONObject repairData = new JSONObject();
                repairData.put("name", "Others");
                repairData.put("stack", "数据报告");
                repairData.put("type", "bar");
                repairData.put("barWidth", "10");
                repairData.put("markLine", "");
                String taskDataUrl = Configuration.getConfigurationByName("hostUrl") + "taskOrderCharts/getHoursData.action";
                JSONArray task = JSONObject.parseArray(HttpClient.doPost(taskDataUrl, dataMap));
                if(task.size()<1) {
                    repairData.put("data", zo);
                } else {
                    repairData.put("data", task);
                }
                data.add(repairData);
            }
        }


        jsonObject.put("dataTitle", dataTitle);
        jsonObject.put("dataName", dataName);
        jsonObject.put("data", data);
        jsonObject.put("code", "00000000");
        jsonObject.put("organizationName", organizationName);

        return ResultUtil.success(jsonObject);
    }
}
